package com.yand.thinkingInJava.thinkingInJava21.threadcooperation;


import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Blocker{

    synchronized void waitingCall(){
     try{
         while(!Thread.interrupted()){
             wait();
             System.out.println(Thread.currentThread());
         }
     }catch (InterruptedException e){

     }
    }

    synchronized void prod(){
        notify();
    }

    synchronized void prodAll(){
        notifyAll();
    }
}

class Task implements Runnable{

    static Blocker blocker = new Blocker();

    @Override
    public void run() {
        System.out.println("=======1===>"+blocker.hashCode());
        blocker.waitingCall();
    }
}

class Task2 implements Runnable{

    static Blocker blocker = new Blocker();

    @Override
    public void run() {
        System.out.println("======2====>"+blocker.hashCode());
        blocker.waitingCall();
    }
}

/**
 * notify 只会唤醒特性加锁的对象的线程 并非所有等待线程 只会在众多等待线程中 唤醒一个
 * notifyAll 在众多的等待特定锁的线程全部唤醒
 */
public class NotifyVsNotifyAll {

    public static void main(String [] args) throws Exception{
        ExecutorService exec = Executors.newCachedThreadPool();
        for(int i = 0 ; i < 5; i ++){
            exec.execute(new Task());
        }

        exec.execute(new Task2());
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            boolean prod = true;
            @Override
            public void run() {
                if(prod){
                    System.out.println("\nnotify()");
                    Task.blocker.prod();
                    prod = false;
                }else{
                    System.out.println("\nnotifyAll()");
                    Task.blocker.prodAll();
                    prod = true;
                }
            }
        }, 400, 400);
        TimeUnit.SECONDS.sleep(5);
        timer.cancel();
        System.out.println("\nTimer canceled");
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Task2.block.prodAll()");
        Task2.blocker.prodAll();
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("\nShutting down");
        exec.shutdownNow();

    }





}
